<?php
class DemandHelper {

	/**
	 * 查看某需求详细记录，如基本信息、items及状态、审批记录
	 */
	static function getDetail($demand_id){
		$demand = Demand::getDetail($demand_id);
		if(!$demand){
			return false;
		}
		$demand['items'] = DemandItems::getByDemand($demand_id);
		return $demand;
	}
        
        /**
	 * 取单号
	 */
	static function getSNO($demand_id){
		$arr = self::getDetail($demand_id);
		return $arr['sno'];
	}

	/**
	 * 依据用户权限取"采购需求"列表，只基本信息
	 */
	static function getAuthList($conditions=null){
		if(UserPrivHelper::check('procsum')){ //是否有汇总需求权限
			$where = '1';
		}
		else{
			$where = "user_id=".UID;
		}
		$where .= $conditions ? " AND ({$conditions})" : '';
		$order = 'audit_flow ASC, addtime DESC';
		$count = Demand::count($where);
		return Db::get('_Demand')->select()->where($where)->order($order)
				->limit(PagerHelper::split2limit($count))->getAll();
	}

	static function hasPurview($demand_id){
		if(UserPrivHelper::check('procsum')){
			return true;
		}
		$d = Demand::get($demand_id);
		if($d && ($d['user_id']==UID)){
			return true;
		}
		return false;
	}

	static function type2text($demand_type,$getlist=false){
		static $sets = array(0=>'补库采购',1=>'专项采购',2=>'紧急采购');
		return $getlist ? $sets : fetch_a_char($demand_type, $sets);
	}

	static function flow2text($audit_flow){
		static $sets = array(0=>'待审',1=>'通过',2=>'失败');
		return fetch_a_char($audit_flow, $sets);
	}

	static function state2text($demand_item_state){
		static $sets = array(0=>'', 1=>'已汇总', 2=>'录入报价', 3=>'采购环节', 9=>'无法采购');
		return fetch_a_char($demand_item_state, $sets);
	}

	/**
	 * 通过订单ID取原始需求ID及材料ID 
	 * @return  array  {'demand_id':{'ware_id', ...}, ,...}
	 */
	static function getItemsByIndent($indent_id){
		$indent = Indent::get($indent_id);
		if(!$indent) return false;
		$list = Db::get('_DemandItems')->select('demand_id, ware_id')->where(array(
					'summary_id' => $indent['summary_id'],
				))->getAll();
		$tmp = array();
		foreach($list as $row){
			if(!isset($tmp[$row['demand_id']])) $tmp[$row['demand_id']] = array();
			$tmp[$row['demand_id']][] = $row['ware_id'];
		}
		return $tmp;
	}
	
}
?>
